﻿package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.ConsumerLog;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.mm.sdk.platformtools.Log;
import com.umeng.analytics.MobclickAgent;
/**
 * 消费明细
 * @author kuanter
 *
 */
public class MyConsumerDetailActivity extends WuyangBaseActivity implements  OnRatingBarChangeListener{
	private TextView my_consumer_detail_include_2_tv_service_kind_title;
	private TextView my_consumer_detail_include_2_tv_outOfPockte_money_title;
	private TextView my_consumer_detail_include_2_tv_trade_status_title;
	private TextView my_consumer_detail_include_2_tv_trade_time_title;
	private int consumerLogIndex ;
	private ConsumerLog consumerLog ;
	private List<ConsumerLog> consumerLogList ;
	private TextView my_consumer_detail_include_2_tv_website_name_data;
	private TextView my_consumer_detail_include_2_tv_service_kind_data;
	private TextView my_consumer_detail_include_2_tv_outOfPockte_money_data;
	private TextView my_consumer_detail_include_2_tv_trade_status_data;
	private TextView my_consumer_detail_include_2_tv_trade_time_data;
	
	private float rating;
	/*private ImageView include_1tv_star_1tv_Star1;
	private ImageView include_1tv_star_1tv_Star2;
	private ImageView include_1tv_star_1tv_Star3;
	private ImageView include_1tv_star_1tv_Star4;
	private ImageView include_1tv_star_1tv_Star5;*/
	
	/*private boolean star1_flag = false;
	private boolean star2_flag = false;
	private boolean star3_flag = false;
	private boolean star4_flag = false;
	private boolean star5_flag = false;*/
	private Button back_btn;
//	private int starNum = 0;
	private TextView tvSiteCredits;
	private ImageView score_iv;
	private DataLoader dataLoader;
	private int userId;
	
	
	IWXAPI wx;
	/**
	 * 打分请求响应
	 */
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
//				finishProgress();
				// String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				Log.i("wuyang", result);
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							showToast("打分成功");							// 字段值是否为false
//								ratingBar.setClickable(false);
								ratingBar.setRating(rating);
								ratingBar.setEnabled(false);
								clickRating = false;
								consumerLog.setVoteState("2");
								ProApplication.setGradeSuccessed(true);
//							finishProgress();
						} else {
//							finishProgress();
							// 显示返回数据中 errorMsg 字段值
							consumerLog.setVoteState("1");
							showToast(StringUtil.geterrorMsg(result));
						}
					} catch (JSONException e) {
//						finishProgress();
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
//					finishProgress();
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
//				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	private RatingBar ratingBar;
	private ImageView shareIV;
	private boolean clickRating = false;
	
	
	public void onResume() {
		MerchantTurnActivity2.sh = false;
		Log.i("ccc", "NyCons onResume");
	    super.onResume();
	    MobclickAgent.onResume(this);
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_consumer_detail);
		ratingBar = (RatingBar)this.findViewById(R.id.ratingBar);
		ratingBar.setOnRatingBarChangeListener(this);
		userId = SharePrefenceUtil.getUserID(this);
		consumerLogIndex = getIntent().getIntExtra("consumerLogIndex", 0);
		consumerLogList = (List<ConsumerLog>)ObjectCache.get("consumerList");
		consumerLog = consumerLogList.get(consumerLogIndex);
//		this.setHeaderControlViewText();
		this.initBodyControlView();
		this.setBodyControlViewText();
		this.registerListener();
		if(null != consumerLog.getScore() && Float.valueOf(consumerLog.getScore())>0){
			consumerLog.setVoteState("2");
		}
//		if("2".equals(consumerLog.getVoteState())){
			if("2".equals(consumerLog.getVoteState())||"1".equals(consumerLog.getState())||"9".equals(consumerLog.getState())){
//			showToast("您上次评过分了哦~");
				ratingBar.setClickable(false);
				ratingBar.setIsIndicator(false);
				ratingBar.setEnabled(false);
			}else if(("1".equals(consumerLog.getVoteState()) && "4".equals(consumerLog.getState()))){
				ratingBar.setEnabled(true);
			}
//		}	
		
		wx = WXAPIFactory.createWXAPI(this, MainConstants.WEIXIN_APP_ID, false);
		wx.registerApp(MainConstants.WEIXIN_APP_ID);
	}


	@Override
	protected void initBodyControlView() {
		// TODO Auto-generated method stub
		View my_consumer_detail_include_2_tv_website_name_item = this.findViewById(R.id.my_consumer_detail_include_2_tv_website_name);
		//数据待定 
		my_consumer_detail_include_2_tv_website_name_data = (TextView) my_consumer_detail_include_2_tv_website_name_item.findViewById(R.id.include_2_tv_TVdata);
		View my_consumer_detail_include_2_tv_service_kind_item = this.findViewById(R.id.my_consumer_detail_include_2_tv_service_kind);
		my_consumer_detail_include_2_tv_service_kind_title =(TextView) my_consumer_detail_include_2_tv_service_kind_item.findViewById(R.id.include_2_tv_TVtitle);
		//数据待定 
		my_consumer_detail_include_2_tv_service_kind_data = (TextView) my_consumer_detail_include_2_tv_service_kind_item.findViewById(R.id.include_2_tv_TVdata);
		my_consumer_detail_include_2_tv_service_kind_data.setTextColor(this.getResources().getColor(R.color.blue));
		View my_consumer_detail_include_2_tv_outOfPockte_money_item =  this.findViewById(R.id.my_consumer_detail_include_2_tv_outOfPockte_money);
		my_consumer_detail_include_2_tv_outOfPockte_money_title = (TextView) my_consumer_detail_include_2_tv_outOfPockte_money_item.findViewById(R.id.include_2_tv_TVtitle);
		//数据待定
		my_consumer_detail_include_2_tv_outOfPockte_money_data = (TextView) my_consumer_detail_include_2_tv_outOfPockte_money_item.findViewById(R.id.include_2_tv_TVdata);
		View my_consumer_detail_include_2_tv_trade_status_item =  this.findViewById(R.id.my_consumer_detail_include_2_tv_trade_status);
		my_consumer_detail_include_2_tv_trade_status_title = (TextView) my_consumer_detail_include_2_tv_trade_status_item.findViewById(R.id.include_2_tv_TVtitle);
		//数据待定
		my_consumer_detail_include_2_tv_trade_status_data = (TextView) my_consumer_detail_include_2_tv_trade_status_item.findViewById(R.id.include_2_tv_TVdata);
		View my_consumer_detail_include_2_tv_trade_time_item = this.findViewById(R.id.my_consumer_detail_include_2_tv_trade_time);
		my_consumer_detail_include_2_tv_trade_time_title = (TextView) my_consumer_detail_include_2_tv_trade_time_item.findViewById(R.id.include_2_tv_TVtitle);
		//数据待定
		my_consumer_detail_include_2_tv_trade_time_data = (TextView) my_consumer_detail_include_2_tv_trade_time_item.findViewById(R.id.include_2_tv_TVdata);
	
		//网点打分
		/*
		include_1tv_star_1tv_Star1 = (ImageView) this.findViewById(R.id.include_1tv_star_1tv_Star1);
		include_1tv_star_1tv_Star2 = (ImageView) this.findViewById(R.id.include_1tv_star_1tv_Star2);
		include_1tv_star_1tv_Star3 = (ImageView) this.findViewById(R.id.include_1tv_star_1tv_Star3);
		include_1tv_star_1tv_Star4 = (ImageView) this.findViewById(R.id.include_1tv_star_1tv_Star4);
		include_1tv_star_1tv_Star5 = (ImageView) this.findViewById(R.id.include_1tv_star_1tv_Star5);*/
		
		back_btn = (Button)this.findViewById(R.id.header_left);
		shareIV = (ImageView)this.findViewById(R.id.header_right);
	}

	@Override
	protected void setBodyControlViewText() {
		// TODO Auto-generated method stub
		my_consumer_detail_include_2_tv_service_kind_title.setText("服务项目：");
		my_consumer_detail_include_2_tv_outOfPockte_money_title.setText("积分消耗：");
		my_consumer_detail_include_2_tv_trade_status_title.setText("交易状态：");
		my_consumer_detail_include_2_tv_trade_time_title.setText("交易时间：");
		//设置数据
		my_consumer_detail_include_2_tv_website_name_data.setText(consumerLog.getConsumptionShop());
		my_consumer_detail_include_2_tv_service_kind_data.setText(consumerLog.getConsumptionType());
		my_consumer_detail_include_2_tv_outOfPockte_money_data.setText(consumerLog.getConsumptionAmount());
		if(null == consumerLog.getState()){
			my_consumer_detail_include_2_tv_trade_status_data.setText("已完成");
		}else {
			switch (Integer.valueOf(consumerLog.getState())) {
			case 1:
				my_consumer_detail_include_2_tv_trade_status_data.setText("处理中");
				break;
			case 4:
				my_consumer_detail_include_2_tv_trade_status_data.setText("已完成");
				break;
			case 9:
				my_consumer_detail_include_2_tv_trade_status_data.setText("已取消");
				break;
			}
		}
		my_consumer_detail_include_2_tv_trade_time_data.setText(consumerLog.getConsumptionTime());
		if(consumerLog.getScore() != null && !consumerLog.getScore().equals("")){
			ratingBar.setRating(Float.valueOf(consumerLog.getScore()));
		}
		score_iv = (ImageView)this.findViewById(R.id.score_iv);
		if(null == consumerLog.getShopConsumptionScore()||"".equals(consumerLog.getShopConsumptionScore())){
			score_iv.setImageResource(R.drawable.point0);
		}else {
			int flag = (int) Math.round(Double.valueOf(consumerLog.getShopConsumptionScore()));
			switch (flag) {
			case 0:
				
				score_iv.setImageResource(R.drawable.point0);
				break;
			case 1:
				score_iv.setImageResource(R.drawable.point10);
				ratingBar.setRating(1);
				break;
			case 2:
				score_iv.setImageResource(R.drawable.point20);
//				ratingBar.setRating(2);
				break;
			case 3:
				score_iv.setImageResource(R.drawable.point30);
//				ratingBar.setRating(3);
				break;
			case 4:
				score_iv.setImageResource(R.drawable.point40);
//				ratingBar.setRating(4);
				break;
			case 5:
				score_iv.setImageResource(R.drawable.point50);
//				ratingBar.setRating(5);
				break;
			}
		}
	}

	@Override
	protected void registerListener() {
		// TODO Auto-generated method stub
		/*include_1tv_star_1tv_Star1.setOnClickListener(this);
		include_1tv_star_1tv_Star2.setOnClickListener(this);
		include_1tv_star_1tv_Star3.setOnClickListener(this);
		include_1tv_star_1tv_Star4.setOnClickListener(this);
		include_1tv_star_1tv_Star5.setOnClickListener(this);*/
		back_btn.setOnClickListener(this);
		shareIV.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		/*case R.id.include_1tv_star_1tv_Star1:
			if(star1_flag == false){
				include_1tv_star_1tv_Star1.setImageResource(R.drawable.btn_star_b_normal);
				star1_flag = true;
				starNum++;
			}else{
				include_1tv_star_1tv_Star1.setImageResource(R.drawable.btn_star_b_pressed);
				star1_flag = false;
				starNum--;
			}
			break;
		case R.id.include_1tv_star_1tv_Star2:
			if(star2_flag == false){
				include_1tv_star_1tv_Star2.setImageResource(R.drawable.btn_star_b_normal);
				star2_flag = true;
				starNum++;
			}else{
				include_1tv_star_1tv_Star2.setImageResource(R.drawable.btn_star_b_pressed);
				star2_flag = false;
				starNum--;
			}
			break;
		case R.id.include_1tv_star_1tv_Star3:
			if(star3_flag == false){
				include_1tv_star_1tv_Star3.setImageResource(R.drawable.btn_star_b_normal);
				star3_flag = true;
				starNum++;
			}else{
				include_1tv_star_1tv_Star3.setImageResource(R.drawable.btn_star_b_pressed);
				star3_flag = false;
				starNum--;
			}
			break;
		case R.id.include_1tv_star_1tv_Star4:
			if(star4_flag == false){
				include_1tv_star_1tv_Star4.setImageResource(R.drawable.btn_star_b_normal);
				star4_flag = true;
				starNum++;
			}else{
				include_1tv_star_1tv_Star4.setImageResource(R.drawable.btn_star_b_pressed);
				star4_flag = false;
				starNum--;
			}
			break;
		case R.id.include_1tv_star_1tv_Star5:
			if(star5_flag == false){
				include_1tv_star_1tv_Star5.setImageResource(R.drawable.btn_star_b_normal);
				star5_flag = true;
				starNum++;
			}else{
				include_1tv_star_1tv_Star5.setImageResource(R.drawable.btn_star_b_pressed);
				star5_flag = false;
				starNum--;
			}
			break;*/
		case R.id.header_left:
			if(rating > 0){
				if(null == consumerLog.getVoteState()||"".equals(consumerLog.getVoteState())){
					//showToast("您未给该网店投票打分哦~");
					dataLoader = new DataLoader(this);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("userId", userId+""));
					params.add(new BasicNameValuePair("id",consumerLog.getId()));
					params.add(new BasicNameValuePair("score", (int)rating+""));
					dataLoader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.GRADE2,
							params, handler, "", false);
//					showProgress("正在加载数据...");
				}else {
					if(!"".equals(consumerLog.getVoteState())){
						switch (Integer.valueOf(consumerLog.getVoteState())) {
						case 1://未投票
							//showToast("您未给该网店投票打分哦~");
							dataLoader = new DataLoader(this);
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							params.add(new BasicNameValuePair("userId", userId+""));
							params.add(new BasicNameValuePair("id",consumerLog.getId()));
							params.add(new BasicNameValuePair("score", (int)rating+""));
							dataLoader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.GRADE2,
									params, handler, "", false);
//							showProgress("正在打分中...");
							break;
						case 2://已投票
//					showToast("您上次评过分了哦~");
//						ratingBar.setRating(rating);
							ratingBar.setIsIndicator(false);
							break;
						}
					}
				}
			}
				
					/*if(null == consumerLog.getVoteState()!"null".equals(consumerLog.getVoteState())&&!"".equals(consumerLog.getVoteState())){
						switch (Integer.valueOf(consumerLog.getVoteState())) {
						case 1://未投票
							//showToast("您未给该网店投票打分哦~");
							dataLoader = new DataLoader(this);
							List<NameValuePair> params = new ArrayList<NameValuePair>();
							params.add(new BasicNameValuePair("userId", userId+""));
							params.add(new BasicNameValuePair("id",consumerLog.getId()));
							params.add(new BasicNameValuePair("score", (int)rating+""));
							dataLoader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.GRADE2,
									params, handler, "", false);
//							showProgress("正在打分中...");
							break;
						case 2://已投票
//					showToast("您上次评过分了哦~");
//						ratingBar.setRating(rating);
							ratingBar.setIsIndicator(false);
							break;
						}
					}*/
			this.finish();
			break;
		case R.id.header_right:
			Builder build = new AlertDialog.Builder(MyConsumerDetailActivity.this).setTitle("分享好友")
			.setItems(R.array.share_item, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(which == 0) {
//						Intent intent = new Intent(Intent.ACTION_MAIN);
//						intent.addCategory(Intent.CATEGORY_DEFAULT);
//						intent.setType("vnd.android-dir/mms-sms");
						Uri uri = Uri.parse("smsto:");
						Intent intent = new Intent(Intent.ACTION_SENDTO,uri);
						intent.putExtra("sms_body", "我在@宽途汽车  的"+consumerLog.getConsumptionShop() +"刷卡消费了一次"+ consumerLog.getConsumptionType()+"，刷卡才"+consumerLog.getFacePrice()+"，很划算，推荐给大家！");
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					} else if(which == 1) {
						/*Intent intent = new Intent(MyConsumerDetailActivity.this, WXEntryActivity.class);
						intent.putExtra("status", 2);
						intent.putExtra("friend", false);
						intent.putExtra("who", ShareActivity.IT);
						intent.putExtra("text", "我在@宽途汽车  的"+consumerLog.getConsumptionShop() +"刷卡消费了一次"+ consumerLog.getConsumptionType()+"，刷卡才"+consumerLog.getConsumptionAmount()+"，很划算，推荐给大家！");
						intent.putExtra("shop", consumerLog.getConsumptionShop());
						intent.putExtra("consumer_type", consumerLog.getConsumptionType());
						intent.putExtra("pay", consumerLog.getConsumptionAmount());
						startActivity(intent);*/
						String text = "我在@宽途汽车  的"+consumerLog.getConsumptionShop() +"刷卡消费了一次"+ consumerLog.getConsumptionType()+"，刷卡才"+consumerLog.getFacePrice()+"，很划算，推荐给大家！";
						WXTextObject textObj = new WXTextObject();
						textObj.text = text;
						WXMediaMessage msg = new WXMediaMessage();
						msg.mediaObject = textObj;
						msg.description = text;
						SendMessageToWX.Req req = new SendMessageToWX.Req();
						req.transaction = buildTransaction("text"); //
						req.message = msg;
						req.scene = SendMessageToWX.Req.WXSceneSession;
					    wx.sendReq(req);
						
						if(dialog != null) {
							dialog.dismiss();
						}
						
						finish();
					}else if(which == 2) {
						/*Intent intent = new Intent(MyConsumerDetailActivity.this, WXEntryActivity.class);
						intent.putExtra("status", 2);
						intent.putExtra("friend", true);
						intent.putExtra("who", ShareActivity.IT);
						intent.putExtra("text", "我在@宽途汽车  的"+consumerLog.getConsumptionShop() +"刷卡消费了一次"+ consumerLog.getConsumptionType()+"，刷卡才"+consumerLog.getConsumptionAmount()+"，很划算，推荐给大家！");
						intent.putExtra("shop", consumerLog.getConsumptionShop());
						intent.putExtra("consumer_type", consumerLog.getConsumptionType());
						intent.putExtra("pay", consumerLog.getConsumptionAmount());
						startActivity(intent);*/
						
						String text = "我在@宽途汽车  的"+consumerLog.getConsumptionShop() +"刷卡消费了一次"+ consumerLog.getConsumptionType()+"，刷卡才"+consumerLog.getFacePrice()+"，很划算，推荐给大家！";
						WXTextObject textObj = new WXTextObject();
						textObj.text = text;
						WXMediaMessage msg = new WXMediaMessage();
						msg.mediaObject = textObj;
						msg.description = text;
						SendMessageToWX.Req req = new SendMessageToWX.Req();
						req.transaction = buildTransaction("text"); //
						req.message = msg;
						req.scene = SendMessageToWX.Req.WXSceneTimeline;
					    wx.sendReq(req);
						
						if(dialog != null) {
							dialog.dismiss();
						}
						finish();
					} else if(which == 3) {
						Intent intent = new Intent(MyConsumerDetailActivity.this, ShareActivity.class);
						intent.putExtra("status", 0);
						intent.putExtra("who", ShareActivity.IT);
						intent.putExtra("shop", consumerLog.getConsumptionShop());
						intent.putExtra("consumer_type", consumerLog.getConsumptionType());
						intent.putExtra("pay", consumerLog.getFacePrice());
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					} else if(which == 4) {
						Intent intent = new Intent(MyConsumerDetailActivity.this, ShareActivity.class);
						intent.putExtra("status", 1);
						intent.putExtra("who", ShareActivity.IT);
						intent.putExtra("shop", consumerLog.getConsumptionShop());
						intent.putExtra("consumer_type", consumerLog.getConsumptionType());
						intent.putExtra("pay", consumerLog.getFacePrice());
						startActivity(intent);
						if(dialog != null) {
							dialog.dismiss();
						}
					}
				}
			});
			AlertDialog dialog = build.create();
			dialog.show();
			break;
		}
	}

	@Override
	protected void getControlViewText() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRatingChanged(RatingBar ratingBar, float rating,
			boolean fromUser) {
		// TODO Auto-generated method stub
		Log.i("wu", rating+"");
		this.rating = rating;
	}
	@Override
	protected void setHeaderControlViewText() {
		// TODO Auto-generated method stub
		
	}
	@Override
	protected void onDestroy() {
		Log.i("ccc", "NyCons onDestory ..WHY????");
		finishProgress();
		super.onDestroy();
	}
	
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
}
